package com.xiangsai;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: paxos-java-demo
 * @description 提案者
 * @author: wzx
 * @create: 2021-07-09 16:37
 **/
public class Proposer implements Runnable {

    int myId=0; //序列号
    private String name; //提案者名称
    private Proposal proposal; //提案者的提案
    //是否已经有提案获得多数派决策者的确认
    private boolean voted;
    //决策者
    private List<Acceptor> acceptors;

    public Proposer(int myId,String name,List<Acceptor> acceptors){
        this.myId=myId;
        this.name=name;
        this.acceptors=acceptors;
        voted=false;
        this.proposal=new Proposal(0,myId+"#Proposal","value:"+myId);
    }

    //准备提案过程，获得多数派决策者支持后，进入提案确认阶段
    public synchronized boolean prepare(){
        int quorum = Math.floorDiv(acceptors.size(), 2) + 1; //一半以上的Acceptor
        PrepareResult prepareResult = null;
        //已获承诺人数
        int promisedCount = 0;
        while(true){
            List<Proposal> promisedProposals = new ArrayList<Proposal>();
            List<Proposal> acceptedProposals = new ArrayList<Proposal>();

            for(Acceptor acceptor : acceptors){
                prepareResult=acceptor.onPrepare(proposal); //提价提案

                if(prepareResult==null)
                    continue;

                if(prepareResult.isPromised())
                {
                    promisedCount++;
                }
                else{
                    //决策者已经给了更高id的承诺
                    if(prepareResult.getAcceptorStatus()==AcceptorStatus.PROMISED){
                        promisedProposals.add(prepareResult.getProposal());
                    }
                    //决策者通过一个议案
                    if(prepareResult.getAcceptorStatus()==AcceptorStatus.ACCEPTED)
                    {
                        acceptedProposals.add(prepareResult.getProposal());
                    }
                }
            }
        }
    }




    public void run() {
        prepare(); //准备提案
    }
}
